//
//  LYBankViewController.swift
//  LYOnlineBanking
//
//  Created by 李永彬 on 2025/8/2.
//

import UIKit

class LYBankViewController: LYAuthBaseViewController {
    var productId: Int?
    var orderNum: String?
    var onomit: Onomit?
    var titleName: String?
    
    var megaloplanesques: [Megaloplanesque] = []
    
    var currentMegaloplanesque: Megaloplanesque? = nil
    
    lazy var tableView: UITableView = {
        let tableView = UITableView()
        tableView.register(LYBankListCell.self, forCellReuseIdentifier: "LYBankListCell")
        tableView.dataSource = self
        tableView.delegate = self
        tableView.separatorStyle = .none
        tableView.rowHeight = UITableView.automaticDimension
        tableView.estimatedRowHeight = 120
        tableView.backgroundColor = .clear
        tableView.shouldIgnoreScrollingAdjustment = true
        tableView.shouldRestoreScrollViewContentOffset = true
        return tableView
    }()
    
    private let topView = LYPersonalTopView()
    
    lazy var submitButton: UIButton = {
        let button = UIButton(type: .custom)
        button.setTitle(LYlocalizedString("Submit"), for: .normal)
        button.layer.masksToBounds = true
        button.layer.cornerRadius = 27.5
        button.addTarget(self, action: #selector(submitAction(_ :)), for: .touchUpInside)
        button.backgroundColor = UIColor(hex: "#1E4FF3")
        button.layer.borderColor = UIColor(hex: "#FFFFFF").cgColor
        button.layer.borderWidth = 1.0
        return button
    }()
    
    var enumAlertView: LYCustomAlertView? = nil
    
    var startTimeStamp = 0.0
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        self.bgImage = nil
        self.view.backgroundColor = UIColor(hex: "#FC7900")
        self.title = self.titleName
        commonInitSubviews()
        fetchData()
        
        startTimeStamp = Date().timeIntervalSince1970
    }
    
    func commonInitSubviews() {
        self.view.addSubview(topView)
        self.view.addSubview(tableView)
        self.view.addSubview(submitButton)
        let aspectRatio = 91.0 / 346.0
        let margin = 15.0
        let height = (SCREEN_WIDTH - margin * 2) * aspectRatio
        topView.snp.makeConstraints { make in
            make.top.equalTo(view.safeAreaLayoutGuide.snp.top)
            make.leading.trailing.equalToSuperview().inset(margin)
            make.height.equalTo(height)
        }
        
        tableView.snp.makeConstraints { make in
            make.top.equalTo(topView.snp.bottom).offset(15)
            make.leading.trailing.equalToSuperview()
            make.bottom.equalTo(submitButton.snp.top).offset(-20)
        }
        
        submitButton.snp.makeConstraints { make in
            make.leading.trailing.equalToSuperview().inset(16)
            make.bottom.equalToSuperview().offset(-bottomMargin)
            make.height.equalTo(55)
        }
    }

    func fetchData() {
        LYHUDUtils.showLoading()
        LYStocksManager.fetchBanksInfo(productId: self.productId ?? -1) { [weak self]  bankData, msg, error in
            guard let self = self else { return }
            if error == nil {
                self.megaloplanesques = bankData?.megaloplanesque ?? []
                self.tableView.reloadData()
                LYHUDUtils.hideHUD()
            } else {
                
                LYHUDUtils.showToast(msg)
            }
        }
    }
    
    func fetchSaveReceiptAccount() {
        LYHUDUtils.showLoading()
        LYStocksManager.fetchSaveBanksInfo(productId: self.productId ?? -1, megaloplanesques: self.megaloplanesques) {  [weak self] success, msg, error in
            guard let self = self else { return }
            if error == nil {
                NotificationCenter.default.post(name: .orderListFollowKey,
                                                object: nil,
                                                userInfo: ["customData": self.onomit as Any,
                                                           "orderNum": self.orderNum ?? ""])
                
                LYTrackingManager.uploadRiskTracking(sceneType: .bankCredential,
                                                     productId: productId,
                                                     orderNum: orderNum,
                                                     startTimeStamp: startTimeStamp,
                                                     endTimeStamp: Date().timeIntervalSince1970)
                LYHUDUtils.hideHUD()
            } else {
                
                LYHUDUtils.showToast(msg)
            }
        }
    }
    
    func showsEnumAlertView(_ phasbooks: [Phasbook]) {
        let enumView = LYPersonalEnumView()
        enumView.dataSource = phasbooks
        enumView.onSelectionChanged = { index, item in
            print("选中索引: \(index), 选中项: \(item?.sarcling ?? "nil")")
        }
        enumView.onConfirmaAction = { [weak self] item in
            guard let self = self else { return }
            self.enumAlertView?.hide { [weak self] in
                guard let self = self else { return }
                self.updateMegaloplanesqueFamiliose(item?.sarcling ?? "",
                                                    storyitious: item?.storyitious)
                self.tableView.reloadData()
            }
        }
        enumAlertView = LYCustomAlertView(view: enumView,
                                          backgroundImage: UIImage(named: "enum_alert_bg"))
        
        // 显示弹窗
        enumAlertView?.show()
    }
    
    @objc func submitAction(_ sender: UIButton) {
        self.view.endEditing(true)
        self.fetchSaveReceiptAccount()
    }
    
    func updateMegaloplanesqueFamiliose(_ familiose: String, storyitious: String? = nil) {
        for (index, megaloplanesque) in self.megaloplanesques.enumerated() {
            if megaloplanesque == self.currentMegaloplanesque {
                self.currentMegaloplanesque?.familiose = familiose
                if let storyitious = storyitious {
                    self.currentMegaloplanesque?.storyitious = storyitious
                }
                if let currentMegaloplanesque = self.currentMegaloplanesque {
                    self.megaloplanesques[index] = currentMegaloplanesque
                }
            }
        }
    }
}

extension LYBankViewController: UITableViewDataSource, UITableViewDelegate {

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return megaloplanesques.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "LYBankListCell", for: indexPath) as! LYBankListCell
        
        cell.didClickButtonClourse = { [weak self] megaloplanesque in
            guard let self = self else { return }
            self.currentMegaloplanesque = megaloplanesque
            if let shotish = megaloplanesque.shotish,
               let type = PersonalListCellType(rawValue: shotish) {
               
                switch type {
                case .enum:
                    guard let phasbooks = megaloplanesque.phasbook else { return }
                    self.showsEnumAlertView(phasbooks)
                case .txt, .citySelect:
                    break
                }
            }
            self.view.endEditing(true)
        }
        
        cell.didTextFieldChanged = { [weak self] megaloplanesque in
            guard let self = self else { return }
            self.currentMegaloplanesque = megaloplanesque
            if let familiose = megaloplanesque.familiose {
                self.updateMegaloplanesqueFamiliose(familiose,
                                                    storyitious: megaloplanesque.storyitious ?? "")
            }
        }

        cell.configure(with: megaloplanesques[indexPath.row])
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        self.view.endEditing(true)
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        let aspectRatio = 91.0 / 346.0
        let imageHeight = (SCREEN_WIDTH - LYBankListCell.leftRMargin * 2) * aspectRatio
        return imageHeight + LYBankListCell.top
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        self.view.endEditing(true)
    }
}

extension LYBankViewController {
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesBegan(touches, with: event)
        self.view.endEditing(true)
    }
}



